package com.fbs.wowo.finance.web;

import com.fbs.wowo.base.BaseController;
import com.fbs.wowo.base.Response;
import com.fbs.wowo.exception.CreateEntityFailedException;
import com.fbs.wowo.finance.service.CashService;
import com.fbs.wowo.util.netutil.NetUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;

/**
 * 提现
 */
@RestController
@RequestMapping("/cash")
public class CashController extends BaseController {

    /**
     * 微信 用户授权 跳转到微信
     * @param userId
     * @param response
     * @return
     * @throws CreateEntityFailedException
     */
    @PostMapping("/wxpreauth")
    public Response preauth(@RequestParam String userId, HttpServletResponse response) throws CreateEntityFailedException {
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
            throw new CreateEntityFailedException(e.getMessage());
        }
        String resp = cashService.wxPreAuthUrl(userId, outputStream);
        return success(resp);
    }

    /**
     * app调用
     * 微信回调 用户授权
     * @param code
     * @param state
     * @return
     */
    @RequestMapping("/wxauth")
    public Response auth(@RequestParam String code, @RequestParam String state) {
        // 用户id作为state?
        // 获取成功
        cashService.wxAuth(code, state);
        return success();
    }

    @GetMapping("/hasBindWX")
    public Response hasBindWX(@RequestParam String userId) {
        return success(cashService.hasBindWX(userId));
    }

    /**
     * 提现
     * @param userId
     * @param fee
     * @param request
     * @return
     */
    @PostMapping("/wxcash")
    public Response wxcash(@RequestParam String userId, @RequestParam String password, @RequestParam BigDecimal fee, HttpServletRequest request) {
        cashService.wxCash(NetUtils.getIpAddress(request), userId, password, fee);
        return success();
    }

    @Autowired
    private CashService cashService;
}
